<?php

header("Content-Type: text/html;charset=utf8");

class UserDb {

    private $mysql;
    private $mongo;
    private $inMongo;

    public function __construct() {
        
    }

    private function initMysql() {
        $this->mysql = new InMysql();
    }

    private function initMongo() {
        $this->inMongo = new InMongo();
        $this->mongo = $this->inMongo->getMongoDb();
    }

    /**
     * 返回启动统计
     * @param type $type s=学生  t=老师
     * @param type $start 开始时间戳
     * @param type $end 结束时间戳
     * @return string
     */
    public function getStartStat($type, $start, $end, $chara) {
        $this->initMongo();
        if ($type == "t") {
            $collection = $this->mongo->t_loading;
            $query = array('uptime' => array('$gt' => intval($start), '$lt' => intval($end)));
        } elseif ($type == "s") {
            if ($chara == "1") {
                //安卓学生端
                $collection = $this->mongo->s_loading;
                $query = array('uptime' => array('$gt' => intval($start), '$lt' => intval($end)), 'UID' => new MongoRegex("/^([\w]+)+$/"));
            } elseif ($chara == "2") {
                //ios学生端
                $collection = $this->mongo->s_loading;
                $query = array('uptime' => array('$gt' => intval($start), '$lt' => intval($end)), 'UID' => new MongoRegex("/-/"));
            }
        } else {
            return "";
        }


        $cursor = $collection->find($query);
        $array = array();
        foreach ($cursor as $doc) {
            $document = $this->inMongo->object_array($doc);
            array_push($array, $document);
        }
        $res['dat'] = $query;
        $res['data'] = $array;
        $res['count'] = $collection->count($query);
        return $res;
    }

    /**
     * 获得激活的
     * @param type $type s=学生  t=老师
     * @param type $start 开始时间戳
     * @param type $end 结束时间戳
     * @return string
     */
    public function getActiveStat($type, $start, $end, $chara) {
        $this->initMysql();
        if ($type == "t") {
            $sql = "select yid as id,acttime as active_time from yct where acttime >= " . $start . " and acttime <= " . $end;
        } elseif ($type == "s") {

            if ($chara == "1") {//1代表安卓学生端
                $sql = "select sid as id,UNIX_TIMESTAMP(active_time) as active_time from student where UNIX_TIMESTAMP(active_time) >= '$start'and UNIX_TIMESTAMP(active_time) <= '$end'and mac NOT LIKE '_'";
            } elseif ($chara == "2") {//2代表ios学生端
                $sql = "select sid as id,UNIX_TIMESTAMP(active_time) as active_time from student where UNIX_TIMESTAMP(active_time) >= '$start'and UNIX_TIMESTAMP(active_time) <= '$end'and find_in_set('_',mac)";
            }
        } else {
            return "";
        }
        return $this->mysql->fetchData($sql);
    }

    /**
     * 获得登录过的教师用户信息
     * @param type $page
     * @param type $pageSize
     * @return type
     */
    public function getTeacherStatMongo($page, $pageSize) {
        $skip = $page * $pageSize;

        $this->initMongo();

        $collection = $this->mongo->t_loading;

        $pipeline = array(
            array(
                '$group' => array(
                    '_id' => '$UID',
                    'uptime' => array('$last' => '$uptime'),
                    'total' => array('$sum' => 1)
                )
            ),
            array(
                '$project' => array(
                    'UID' => '$_id.UID',
                    'uptime' => '$uptime',
                    'total' => '$total',
                )
            ),
            array(
                '$skip' => $skip
            ),
            array(
                '$limit' => $pageSize
            )
        );

        $batch = array('cursor' => array('batchSize' => 0));
        $cursor = $collection->aggregateCursor($pipeline, $batch);
        $array = array();
        foreach ($cursor as $doc) {
            $document = $this->inMongo->object_array($doc);
            array_push($array, $document);
        }
        $res['data'] = $array;
        $cursor2 = $collection->distinct("UID");
        $res['count'] = count($cursor2);
        return $res;
    }

    /**
     * 获得活跃用户数
     * @param type $teacherIds
     * @return type
     */
    public function getUserActive() {
        $motnTime = 30 * 24 * 60 * 60; //一个月的时间戳
        $time = time(); //当前时间
        $preTime = $time - $motnTime; //当前时间的一个月前的时间戳

        $this->initMongo();
        $collection = $this->mongo->t_loading;
        $cursor1 = $collection->distinct("UID");
        $res['teacherTotal'] = count($cursor1);

        $query = array('uptime' => array('$gt' => $preTime));
        $cursor2 = $collection->find($query);
        $teacherMap = array();
        foreach ($cursor2 as $doc) {
            $document = $this->inMongo->object_array($doc);
            $uid = $document['UID'];

            if (!key_exists($uid, $teacherMap)) {
                $teacherMap[$uid] = $uid;
            }
        }
        $res['teacherActiveCount'] = count($teacherMap);

        $res['teacherStarttime'] = 0;
        $cursor21 = $collection->find(array())->limit(1);
        foreach ($cursor21 as $doc) {
            $document = $this->inMongo->object_array($doc);
            $res['teacherStarttime'] = $document['uptime'];
        }


        $collection3 = $this->mongo->s_loading;
        $cursor3 = $collection3->distinct("UID");
        $res['studentTotal'] = count($cursor3);

        $query3 = array('uptime' => array('$gt' => $preTime));
        $cursor4 = $collection3->find($query3);
        $studentMap = array();
        foreach ($cursor4 as $doc) {
            $document = $this->inMongo->object_array($doc);
            $uid = $document['UID'];

            if (!key_exists($uid, $studentMap)) {
                $studentMap[$uid] = $uid;
            }
        }
        $res['studentActiveCount'] = count($studentMap);

        $res['studentStarttime'] = 0;
        $cursor31 = $collection3->find(array())->limit(1);
        foreach ($cursor31 as $doc) {
            $document = $this->inMongo->object_array($doc);
            $res['studentStarttime'] = $document['uptime'];
        }

        $res['active'] = 0;

        $res['noActive'] = 0;
        return $res;
    }

    /**
     * 获得老师的设备注册信息
     * @param type $teacherIds
     * @return type
     */
    public function getTeacherStatMySql($teacherIds) {
        $this->initMysql();
        $sql = "select * from yct where mac in($teacherIds) group by mac";
        return $this->mysql->fetchData($sql);
    }

    /**
     * 根据业务获取教师字段
     * @param type $page
     * @param type $pageSize
     * @return type
     */
    public function getTeacherList($page, $pageSize) {
        $start = $page * $pageSize;
        $this->initMysql();
        $sql = "select *,(select count(id) from teacher_action where tid = teacher_id) as startCount,
(select create_time from teacher_action where tid = teacher_id order by id desc limit 1) as lastStartTime,
(select count(id) from class_teacher where tid = teacher.tid) as classCount,
(select count(id) from class_student where cid in (select cid from class_teacher where tid = teacher.tid)) as studentCount,
(select sname from school where scid = (select scid from school_teacher where tid = teacher.tid limit 1)) as schoolName,
(select zone from school where scid = (select scid from school_teacher where tid = teacher.tid limit 1)) as zone
 from teacher limit " . $start . "," . $pageSize;
        return $this->mysql->fetchData($sql);
    }

    /**
     * 获取所有教师
     * @return type
     */
    public function getAllTeacher() {
        $this->initMysql();
        $sql = "select * from teacher";
        return $this->mysql->fetchData($sql);
    }

    /**
     * 获取区域
     * @return type
     */
    public function getZone() {
        $this->initMysql();
        $sql = "select * from zone";
        return $this->mysql->fetchData($sql);
    }

    public function getUserStat($type, $deviceId) {
        $this->initMysql();
        if ($type == "t") {
            $sql = "select mac from yct where mac = '" . $deviceId . "' or keyvalue = '" . $deviceId . "'";
        } elseif ($type == "s") {
            $sql = "select mac from student where mac = '" . $deviceId . "'";
        } else {
            return "";
        }
        $macArray = $this->mysql->fetchData($sql);

        if (count($macArray) > 0) {
            $UID = $macArray[0]['mac'];
        } else {
            $res['data'] = array();
            $res['count'] = 0;
            return $res;
        }

        $this->initMongo();
        if ($type == "t") {
            $collection = $this->mongo->t_loading;
        } elseif ($type == "s") {
            $collection = $this->mongo->s_loading;
        } else {
            $res['data'] = array();
            $res['count'] = 0;
            return $res;
        }

        $query = array('UID' => $UID);

        $cursor = $collection->find($query);
        $array = array();
        foreach ($cursor as $doc) {
            $document = $this->inMongo->object_array($doc);
            array_push($array, $document);
        }

        return $collection->count($query);
    }

    public function getUserStatByPage($type, $deviceId, $page, $pageSize) {
        $skip = $page * $pageSize;
        $this->initMysql();
        if ($type == "t") {
            $sql = "select mac from yct where mac = '" . $deviceId . "' or keyvalue = '" . $deviceId . "'";
        } elseif ($type == "s") {

            $sql = "select mac from student where mac = '" . $deviceId . "'";
        } else {
            return "";
        }
        $macArray = $this->mysql->fetchData($sql);

        if (count($macArray) > 0) {
            $UID = $macArray[0]['mac'];
        } else {
            $res['data'] = array();
            $res['count'] = 0;
            return $res;
        }

        $this->initMongo();
        if ($type == "t") {
            $collection = $this->mongo->t_loading;
        } elseif ($type == "s") {
            $collection = $this->mongo->s_loading;
        } else {
            $res['data'] = array();
            $res['count'] = 0;
            return $res;
        }

        $query = array('UID' => $UID);

        $cursor = $collection->find($query)->skip($skip)->limit($pageSize);
        $array = array();
        foreach ($cursor as $doc) {
            $document = $this->inMongo->object_array($doc);
            array_push($array, $document);
        }

        return $array;
    }

    /**
     * 删除老师的设备注册信息
     * @param type $id
     * @return type
     */
    public function del_user($id) {
        $this->initMysql();
        $sql = "delete from yct  where yid = " . $id;
        return $this->mysql->executeData($sql);
    }

    /**
     * 查询教师昵称字段
     * @param type $keyword
     * @return type
     */
    public function searchUser($keyword) {
        $this->initMysql();
        $sql = "select *,(select count(id) from teacher_action where tid = teacher_id) as startCount,
(select create_time from teacher_action where tid = teacher_id order by id desc limit 1) as lastStartTime,
(select count(id) from class_teacher where tid = teacher.tid) as classCount,
(select count(id) from class_student where cid in (select cid from class_teacher where tid = teacher.tid)) as studentCount,
(select sname from school where scid = (select scid from school_teacher where tid = teacher.tid limit 1)) as schoolName,
(select zone from school where scid = (select scid from school_teacher where tid = teacher.tid limit 1)) as zone
 from teacher where nick like '%" . $keyword . "%' or uname like '%" . $keyword . "%'";
        return $this->mysql->fetchData($sql);
    }

    public function searchUserInMongo($UID) {
        $this->initMongo();

        $collection = $this->mongo->t_loading;

        $query = array('UID' => $UID);
        $count = $collection->count($query);

        $cursor1 = $collection->find($query);
        foreach ($cursor1 as $doc) {
            $document = $this->inMongo->object_array($doc);
            $result['first'] = $document['uptime'];
            break;
        }

        $cursor = $collection->find($query);
        $cursor->sort(array("uptime" => -1));
        $array = array();
        foreach ($cursor as $doc) {
            $document = $this->inMongo->object_array($doc);
            $result['last'] = $document['uptime'];
            break;
        }

        $result['count'] = $count;
        return $result;
    }

}
